// 横屏个人页面
class ProfilePage {
  constructor(canvas, ctx, gameManager, api, rootImgUrl) {
    this.canvas = canvas;
    this.ctx = ctx;
    this.gameManager = gameManager;
    this.api = api
    this.rootImgUrl = rootImgUrl
    this.avatar = wx.createImage();
    this.backIcon = wx.createImage();
    this.challengeIcon = wx.createImage();
    this.rankingIcon = wx.createImage();
    this.challengeIconSelect = wx.createImage();
    this.rankingIconSelect = wx.createImage();
    this.mainBg = wx.createImage();
    this.current = 1;

    // 自适应屏幕尺寸
    // this.setupCanvasSize();

    // 列表区域配置（按比例缩放）
    this.scaleRatio = Math.min(this.canvas.width / 1624, this.canvas.height / 750);

    this.listX = 192 * this.scaleRatio;
    this.listY = 104 * this.scaleRatio;
    this.listWidth = 1006 * this.scaleRatio;
    this.listHeight = 636 * this.scaleRatio;

    // 表头配置
    this.headers = ['排名', '姓名', '资金', '投资次数', '胜率'];
    this.headerHeight = 74 * this.scaleRatio;

    // 列表项配置
    this.itemHeight = 74 * this.scaleRatio;
    this.itemSpacing = 10 * this.scaleRatio;
    this.itemPadding = 15 * this.scaleRatio;

    // 数据和滚动
    this.data = [];
    this.visibleStart = 0;
    this.visibleEnd = 0;
    this.scrollTop = 0;
    this.maxScrollTop = 0;

    // 触摸相关
    this.touchStartY = 0;
    this.touchStartTime = 0;
    this.lastTouchY = 0;
    this.velocityY = 0;
    this.isScrolling = false;
    this.animationId = null;

    // 分页配置
    this.pageSize = 20;
    this.currentPage = 1;
    this.isLoading = false;
    this.hasMore = true;
  }

  onEnter() {
    // this.setupCanvasSize();
    this.loadResources();
    console.log('进入横屏排行榜页面');
  }

  onLeave() {
    console.log('离开排行榜页面');
  }

  update() {
    // 个人页面的更新逻辑
  }

  setupCanvasSize() {
    // 获取屏幕尺寸
    const screenWidth = window.innerWidth;
    const screenHeight = window.innerHeight;

    // 设置canvas尺寸
    this.canvasWidth = screenWidth;
    this.canvasHeight = screenHeight;

    this.canvas.width = this.canvasWidth;
    this.canvas.height = this.canvasHeight;

    // 设置字体大小（响应式）
    this.baseFontSize = Math.max(12, Math.min(18, screenWidth / 80));
  }

  loadResources() {
    // 加载头像图片
    this.avatar.src = this.rootImgUrl + 'avatars.png';
    // 加载返回按钮图标
    this.backIcon.src = this.rootImgUrl + 'backIcon.png';
    // 背景图
    this.mainBg.src = this.rootImgUrl + 'rankingBg.png';
    // 加载排位赛图片
    this.rankingIcon.src = this.rootImgUrl + 'rankingIcon.png';
    this.rankingIconSelect.src = this.rootImgUrl + 'rankingIconSelect.png';
    // 加载挑战赛图片
    this.challengeIcon.src = this.rootImgUrl + 'challengeIcon.png';
    this.challengeIconSelect.src = this.rootImgUrl + 'challengeIconSelect.png';

    // 资源加载完成后开始渲染
    let loadedCount = 0;
    const totalResources = 6;

    const checkLoaded = () => {
      loadedCount++;
      if (loadedCount === totalResources) {
        this.loadInitialData();
      }
    };

    this.avatar.onload = checkLoaded;
    this.mainBg.onload = checkLoaded;
    this.backIcon.onload = checkLoaded;
    this.rankingIcon.onload = checkLoaded;
    this.challengeIcon.onload = checkLoaded;
    this.rankingIconSelect.onload = checkLoaded;
    this.challengeIconSelect.onload = checkLoaded;
  }

  render() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    // 横屏个人页面背景
    this.ctx.drawImage(this.mainBg, 0, 0, this.canvas.width, this.canvas.height);

    const userData = this.gameManager.getUserData();
    this.drawLeftSection();
    this.drawTopSection();
    this.drawRightSection();

    // 绘制表头
    this.drawHeader();

    // 设置裁剪区域
    this.ctx.save();
    this.ctx.beginPath();
    this.ctx.rect(
      this.listX,
      this.listY + this.headerHeight,
      this.listWidth,
      this.listHeight - this.headerHeight
    );
    this.ctx.clip();

    // 绘制可见列表项
    this.drawVisibleItems();

    // 恢复裁剪区域
    this.ctx.restore();
  }

  // 获取数据
  async loadInitialData() {
    try {
      this.data = await this.fetchData(1);
      this.updateVisibleRange();
      this.render();
    } catch (error) {
      console.error('初始数据加载失败:', error);
    }
  }

  //加载数据
  async loadMoreData() {
    if (this.isLoading || !this.hasMore) return;

    this.isLoading = true;

    try {
      this.currentPage++;
      const newData = await this.fetchData(this.currentPage);

      if (newData.length < this.pageSize) {
        this.hasMore = false;
      }

      this.data = [...this.data, ...newData];
      this.updateVisibleRange();
      this.render();
    } catch (error) {
      console.error('加载数据失败:', error);
    } finally {
      this.isLoading = false;
    }
  }

  // 请求接口数据
  async fetchData(page) {
    // 模拟API请求
    return new Promise((resolve) => {
      setTimeout(() => {
        const mockData = [];
        const start = (page - 1) * this.pageSize;

        for (let i = 0; i < this.pageSize; i++) {
          const index = start + i + 1;
          mockData.push({
            rank: index,
            name: `用户${index}`,
            capital: (Math.random() * 1000000 + 100000).toFixed(2),
            investCount: Math.floor(Math.random() * 100) + 1,
            winRate: (Math.random() * 100).toFixed(2) + '%'
          });
        }

        resolve(mockData);
      }, 300);
    });
  }

  //判断是否还有数据
  shouldLoadMore() {
    if (this.maxScrollTop <= 0) return false;
    const scrollPercent = this.scrollTop / this.maxScrollTop;
    return scrollPercent > 0.7 && !this.isLoading && this.hasMore;
  }

  //变更可绘制列表区域
  updateVisibleRange() {
    const contentHeight = this.data.length * (this.itemHeight + this.itemSpacing);
    this.maxScrollTop = Math.max(0, contentHeight - (this.listHeight - this.headerHeight));

    const visibleHeight = this.listHeight - this.headerHeight;
    const itemTotalHeight = this.itemHeight + this.itemSpacing;

    this.visibleStart = Math.floor(this.scrollTop / itemTotalHeight);
    this.visibleEnd = Math.min(
      this.data.length - 1,
      Math.ceil((this.scrollTop + visibleHeight) / itemTotalHeight)
    );
  }

  //绘制顶部区域
  drawTopSection() {
    //绘制顶部返回按钮
    this.ctx.drawImage(this.backIcon, 78, 28, 28, 42);

    // 绘制“排行榜”文字
    this.ctx.fillStyle = '#8A98CC';
    this.ctx.font = '52px Microsoft YaHei-Regular';
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';
    this.ctx.fillText('排行榜', this.canvas.width / 2, 55); // x,y
  }

  //绘制左边菜单栏区域
  drawLeftSection() {
    // “排位赛”按钮（带图标）
    this.ctx.drawImage(this.current == 1 ? this.rankingIconSelect : this.rankingIcon, 42, 138, 106, 108);
    this.ctx.fillStyle = this.current == 1 ? '#EBCC4F' : '#fff';
    this.ctx.textAlign = 'center';
    this.ctx.font = 'bold 36px Microsoft YaHei-Regular';
    this.ctx.fillText('排位赛', 96, 300); // x,y

    // “挑战赛”按钮（带图标）
    this.ctx.drawImage(this.current == 2 ? this.challengeIconSelect : this.challengeIcon, 52, 364, 96, 88);
    this.ctx.fillStyle = this.current == 2 ? '#EBCC4F' : '#fff';
    this.ctx.fillText('挑战赛', 96, 510); // x,y
  }

  //绘制表头
  drawHeader() {
    const headerY = this.listY;

    // 表头文字
    this.ctx.fillStyle = '#ffffff';
    this.ctx.font = `${this.baseFontSize * 1.2}px Microsoft YaHei-Regular`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    const columnWidth = this.listWidth / this.headers.length;
    this.headers.forEach((header, index) => {
      const x = this.listX + columnWidth * index + columnWidth / 2;
      const y = headerY + this.headerHeight / 2;
      this.ctx.fillText(header, x, y);
    });
  }

  // 判断可绘制列表区域
  drawVisibleItems() {
    const itemTotalHeight = this.itemHeight + this.itemSpacing;
    const startY = this.listY + this.headerHeight;

    for (let i = this.visibleStart; i <= this.visibleEnd; i++) {
      if (i >= this.data.length) break;

      const item = this.data[i];
      const itemY = startY + i * itemTotalHeight - this.scrollTop;

      // 只绘制在可视区域内的项目
      if (itemY + this.itemHeight < this.listY || itemY > this.listY + this.listHeight) {
        continue;
      }

      this.drawItem(item, itemY, i);
    }
  }

  //绘制列表项
  drawItem(item, y, index) {
    const itemX = this.listX + this.itemPadding;
    const itemWidth = this.listWidth - this.itemPadding * 2;

    // 创建渐变背景
    const gradient = this.ctx.createLinearGradient(
      itemX, 0, itemX + itemWidth, 0
    );
    gradient.addColorStop(0, '#BFB998');
    gradient.addColorStop(0.5, '#47485E');
    gradient.addColorStop(1, '#3E335B');

    // 绘制项目背景
    this.ctx.fillStyle = gradient;
    this.ctx.fillRect(itemX, y, itemWidth, this.itemHeight);

    // 添加边框
    this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.3)';
    this.ctx.lineWidth = 1;
    this.ctx.strokeRect(itemX, y, itemWidth, this.itemHeight);

    // 绘制文字
    this.ctx.fillStyle = '#ffffff';
    this.ctx.font = `${this.baseFontSize}px Arial`;
    this.ctx.textAlign = 'center';
    this.ctx.textBaseline = 'middle';

    const columnWidth = itemWidth / this.headers.length;
    const values = [item.rank, item.name, item.capital, item.investCount, item.winRate];

    values.forEach((value, colIndex) => {
      const x = itemX + columnWidth * colIndex + columnWidth / 2;
      const textY = y + this.itemHeight / 2;

      // 特殊样式
      if (colIndex === 0) { // 排名
        this.ctx.font = `bold ${this.baseFontSize * 1.3}px Arial`;
        this.ctx.fillStyle = index < 3 ? '#FFD700' : '#ffffff';
      } else if (colIndex === 4) { // 胜率
        const winRate = parseFloat(value);
        this.ctx.fillStyle = winRate > 60 ? '#4CAF50' : winRate > 40 ? '#FFC107' : '#F44336';
        this.ctx.font = `bold ${this.baseFontSize}px Arial`;
      } else {
        this.ctx.font = `${this.baseFontSize}px Arial`;
        this.ctx.fillStyle = '#ffffff';
      }

      this.ctx.fillText(value, x, textY);
    });
  }

  drawRightSection() {
    // 右侧个人排名（深蓝色背景）
    // this.ctx.fillStyle = '#666';
    // this.ctx.fillRect(1198, 104, 426, 646); // x,y,width,height

    // 头像（圆形，示例用美食图片）
    this.ctx.drawImage(this.avatar, 1245, 220, 112, 112);

    // 姓名
    this.ctx.fillStyle = '#fff';
    this.ctx.textAlign = 'left';
    this.ctx.font = '28px Microsoft YaHei-Regular';
    this.ctx.fillText('我的排名', 1226, 150); // x,y

    this.ctx.fillText('天心区巴菲特', 1390, 288); // x,y

    // 排名
    this.ctx.font = 'bold 40px Microsoft YaHei-Regular';
    this.ctx.fillText('排名：', 1262, 398); // x,y
    this.ctx.font = 'bold 68px Microsoft YaHei-Regular';
    this.ctx.fillText('325', 1442, 394); // x,y

    // 资金、投资次数、胜率
    this.ctx.font = '28px Microsoft YaHei-Regular';
    this.ctx.fillText('资金：331,331.00', 1266, 494); // x,y
    this.ctx.fillText('投资次数：1234', 1266, 554); // x,y
    this.ctx.fillText('胜率：20%', 1266, 614); // x,y
  }

  handleTouch(x, y) {
    // 检查是否点击了返回按钮
    if (x >= 39 && x <= 70 && y >= 14 && y <= 35) {
      this.gameManager.switchPage('main');
    }
    // 检查是否点击了左侧菜单按钮
    if (x >= 23 && x <= 50) {
      // 检查是否点击了排位赛按钮
      if (y >= 70 && y <= 170) {
        this.current = 1
      }
      // 检查是否点击了挑战赛按钮 
      else if (y >= 182 && y <= 280) {
        this.current = 2
      }
    }
    if (x >= 96 && x <= 598 && y >= 52 && y <= 375) {
      this.touchStartY = y;
      this.lastTouchY = y;
      this.touchStartTime = Date.now();
      this.velocityY = 0;
      this.isScrolling = true;

      // 停止惯性滚动
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.animationId = null;
      }
    }
  }

  handleKeyDown(e) {
    if (e.keyCode === 32) {

    }
  }

  handleTouchMove(x, y) {
    if (!this.isScrolling) return;

    const deltaY = this.lastTouchY - y;

    // 计算速度
    const currentTime = Date.now();
    const timeDelta = currentTime - this.touchStartTime;
    if (timeDelta > 0) {
      this.velocityY = deltaY / timeDelta * 1000;
    }

    this.handleScroll(deltaY);

    this.lastTouchY = y;
    this.touchStartTime = currentTime;
  }

  handleTouchEnd(e) {
    // e.preventDefault();
    this.isScrolling = false;

    // 惯性滚动
    if (Math.abs(this.velocityY) > 50) {
      this.inertiaScroll();
    }
  }

  inertiaScroll() {
    const friction = 0.95;
    const minVelocity = 10;

    const animate = () => {
      if (Math.abs(this.velocityY) < minVelocity) {
        this.animationId = null;
        return;
      }

      const deltaY = this.velocityY * 0.016; // 60fps
      this.handleScroll(deltaY);

      this.velocityY *= friction;
      this.animationId = requestAnimationFrame(animate);
    };

    animate();
  }

  handleScroll(deltaY) {
    const newScrollTop = Math.max(0, Math.min(this.maxScrollTop, this.scrollTop + deltaY));

    if (newScrollTop !== this.scrollTop) {
      this.scrollTop = newScrollTop;
      this.updateVisibleRange();

      // 检查是否需要加载更多数据
      if (this.shouldLoadMore()) {
        this.loadMoreData();
      }

      this.render();
    }
  }

}

export default ProfilePage;